import java.util.concurrent.*;

/**
 * Create by chenhd on 2021/8/28.
 * 方法十五：使用CompletionService，实际上CompletionService底层也是用的阻塞队列
 */
public class ConcurrentTask15 {
    public String str;
    public BlockingQueue<String> blockingQueue = new ArrayBlockingQueue<>(1);

    public static void main(String[] args) throws InterruptedException {
        ConcurrentTask15 concurrentTask = new ConcurrentTask15();

        ExecutorService executorService = Executors.newSingleThreadExecutor();
        Callable<String> callable = () -> {
            concurrentTask.putStr();
            return "ok";
        };

        //这里阻塞队列可以不传，不传默认就是无界的LinkedBlockingQueue，生产环境中尽量慎用无界队列，除非明确知道有多少任务
        CompletionService<String> completionService = new ExecutorCompletionService<>(executorService, new ArrayBlockingQueue<>(1));
        completionService.submit(callable);
        completionService.take();
        System.out.println(concurrentTask.getStr());
        executorService.shutdown();
    }

    public void putStr() {
        try {
            TimeUnit.SECONDS.sleep(5);
            this.str = "hello concurrent.";
            blockingQueue.add("ok");
        } catch (InterruptedException e) {
            //log error
            e.printStackTrace();
        }
    }

    public String getStr() {
        return str;
    }
}
